package com.ada.secure;

import javax.crypto.KeyAgreement;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPublicKey;

public class DiffieHellmanExample {
    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DiffieHellman");
        keyPairGenerator.initialize(512); // Key size
        KeyPair aliceKeyPair = keyPairGenerator.generateKeyPair();
        KeyPair bobKeyPair = keyPairGenerator.generateKeyPair();

        KeyAgreement aliceKeyAgreement = KeyAgreement.getInstance("DiffieHellman");
        aliceKeyAgreement.init(aliceKeyPair.getPrivate());
        aliceKeyAgreement.doPhase(bobKeyPair.getPublic(), true);

        KeyAgreement bobKeyAgreement = KeyAgreement.getInstance("DiffieHellman");
        bobKeyAgreement.init(bobKeyPair.getPrivate());
        bobKeyAgreement.doPhase(aliceKeyPair.getPublic(), true);

        byte[] aliceSharedSecret = aliceKeyAgreement.generateSecret();
        byte[] bobSharedSecret = bobKeyAgreement.generateSecret();

        System.out.println("Alice's shared secret: " + byteArrayToHex(aliceSharedSecret));
        System.out.println("Bob's shared secret: " + byteArrayToHex(bobSharedSecret));
    }

    public static String byteArrayToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02X", b));
        }
        return result.toString();
    }
}
